<?php
declare (strict_types = 1);

namespace app\index\model;

use think\Exception;
use think\facade\Db;

class PresellCommodity extends BaseModel
{
    protected $globalScope = ['mallId'];

    public function commodity()
    {
        return $this->hasOne(Commodity::class, 'id', 'commodity_id')->bind(['name']);
    }

    public function sku()
    {
        return $this->hasMany(PresellCommoditySku::class, 'gc_id', 'id');
    }

    public function presell()
    {
        return $this->belongsTo(Presell::class, 'presell_id', 'id');
    }

    public static function check($commodity_id, $sku_id, $user, $num)
    {
        $presell = PresellCommodity::where('status', '1')
            ->where('commodity_id', $commodity_id)
            ->find();
        if (empty($presell) || $presell['end_time'] < date('Y-m-d H:i:s')) {
            throw new Exception("活动已结束！", HTTP_NOTACCEPT);
        }
        $sc = $presell->toArray();
        unset($sc['end_time']);
        if ($sku_id > 0) {
            $sku = PresellCommoditySku::where('pc_id', $presell['id'])
                ->where('sku_id', $sku_id)
                ->find()
                ->toArray();
            unset($sku['id']);
            $sc = array_merge($sc, $sku);
        }
        // 拼团库存
        if ($sc['activity_stock'] <= 0) {
            throw new Exception("拼团库存紧张！", HTTP_NOTACCEPT);
        }

        // 限购
        $limit_type = json_decode($sc['limit_type']);
        if ($limit_type[$limit_type[0]] != 0) {
            $where = [
                'o.user_id' => $user['id'],
                'c.pc_id' => $sc['id'],
                'c.commodity_id' => $commodity_id,
                'c.status' => ['in', '2,3,4,5,7,8,9,10']//订单状态: 1-待支付 2-待发货 3-已发货 4-已完结 5-已评价   6-删除 7-已收货 8-维权中 9-已维权 10-维权驳回 11-已关闭
            ];
            if ($sku_id > 0) {
                array_push($where, ['c.sku_id' => $sku_id]);
            }

            if ($limit_type[0] == 1) {
                $count = OrderCommodity::alias('c')
                        ->join('order o', 'c.order_id = o.id', 'LEFT')
                        ->where($where)
                        ->count('c.count') + $num;
                $limit = $limit_type[1] - $count;
            } else {
                $count = OrderCommodity::alias('c')
                        ->join('order o', 'c.order_id = o.id', 'LEFT')
                        ->where($where)
                        ->whereTime('create_time', 'between', [
                            date('Y-m-d H:i:s',strtotime(date('Y-m-d'))), strtotime(date('Y-m-d',strtotime('+1 day')))
                        ])->count('c.count') + $num;
                $limit = $limit_type[2] - $count;
            }
            if ($limit < 0) {
                throw new Exception("份额已达上线！", HTTP_NOTACCEPT);
            }
        }
        return $sc;
    }


    /**
     * 加库存
     * @param $sc_id
     * @param $count
     * @param $sku_id
     * @throws
     */
    public static function incStock($sc_id, $count, $sku_id)
    {
        if (is_null($sku_id)) {
            Db::name('presell_commodity')
                ->where('id', $sc_id)
                ->inc("activity_stock", $count)->update();
        } else {
            Db::name('presell_commodity_sku')
                ->where('pc_id', $sc_id)
                ->where('sku_id', $sku_id)
                ->inc("activity_stock", $count)->update();
        }
    }


    /**
     * 减库存
     * @param $sc_id
     * @param $count
     * @param $sku_id
     * @throws
     */
    public static function decStock($sc_id, $count, $sku_id)
    {
        if (is_null($sku_id)) {
            PresellCommodity::where('id', $sc_id)
                ->dec('activity_stock', $count)
                ->update();
        } else {
            PresellCommoditySku::where('pc_id', $sc_id)
                ->where('sku_id', $sku_id)
                ->dec('activity_stock', $count)
                ->update();
        }
    }

}
